﻿using IM.Easy.Core.AppContext;
using IM.Easy.Entity.Log;
using IM.Easy.Infrastructure.Query;
using IM.Easy.LogServices.Dtos;
using IM.Easy.LogServices.IServices;
using IM.Easy.LogServices.Services;
using IM.Easy.SystemServices.Dtos;
using IM.Easy.SystemServices.IServices;
using Mapster;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Drawing.Printing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace IM.Easy.Api.AccountManage
{
    public class OnlineService : IOnlineService
    {
        // 使用 connectionId 作为键，connectionId 作为值
        //private readonly Dictionary<string, string> _userConnections = [];
        private readonly List<UserOnlineLogDto> _userConnections = [];
        public List<UserOnlineLogDto> UserConnections { get { return _userConnections; } }
        private readonly IUserOnlineLogService userOnlineLogService;
        private readonly IRequestTrackingService requestTrackingService;
        private readonly AccountService accountService;

        public OnlineService(IUserOnlineLogService userOnlineLogService, AccountService accountService, IRequestTrackingService requestTrackingService)
        {
            this.userOnlineLogService = userOnlineLogService;
            this.accountService = accountService;
            this.requestTrackingService = requestTrackingService;
        }



        /// <summary>
        /// 添加用户信息。
        /// </summary>
        /// <param name="userId">用户的唯一标识。</param>
        /// <param name="connectionId">SignalR 的连接 ID。</param>
        public void Online(string userId, string connectionId)
        {
            lock (_userConnections)
            {
                var track = requestTrackingService.GetCurrentInfo();
                var account = accountService.GetCurrent();
                var user = new UserOnlineLogDto
                {
                    UserId = userId,
                    ConnectionId = connectionId,
                    OnlineTime = DateTime.Now,
                };
                _userConnections.Add(user);
                var instance = user.Adapt<UserOnlineLog>();
                instance.UserName = account.UserName;
                instance.NickName = account.NickName;
                instance.IpAddress = track.Address;
                instance.ClientIP = track.ClientIP;
                instance.UserAgent = track.UserAgent;
                userOnlineLogService.Create(instance);
            }
        }


        /// <summary>
        /// 移除用户信息。
        /// </summary>
        /// <param name="connectionId">SignalR 的连接 ID。</param>
        public UserOnlineLogDto Offline(string connectionId)
        {
            lock (_userConnections)
            {
                _userConnections.RemoveAll(u => u.ConnectionId == connectionId);
                var user = userOnlineLogService.GetUserOnlineLog(connectionId).FirstOrDefault();
                if (user != null)
                {
                    user.OfflineTime = DateTime.Now;
                    userOnlineLogService.Update(user.Adapt<UserOnlineLog>());
                }
                return user;
            }
        }

        /// <summary>
        /// 获取分页后的用户信息。
        /// </summary>
        /// <param name="query">查询参数。</param>
        /// <returns>返回分页结果。</returns>
        public PageResponse<UserOnlineLogDto> GetUsers(UserOnlineLogQueryDto query)
        {
            lock (_userConnections)
            {
                var response = new PageResponse<UserOnlineLogDto>();
                var users = _userConnections.OrderBy(s => s.OnlineTime).AsEnumerable();
                var connid = users.WhereIF(!string.IsNullOrEmpty(query.UserName), s => s.UserName == query.UserName)
                             .Skip((query.PageIndex - 1) * query.PageSize).Take(query.PageSize)
                             .Select(s => s.ConnectionId)
                             .ToArray();
                var result = userOnlineLogService.GetUserOnlineLog(connid);
                response.Result = result;
                response.TotalNum = _userConnections.Count;
                return response;
            }
        }

        /// <summary>
        /// 根据 userId 获取 connectionId。
        /// </summary>
        public string? GetConnectionIdByUserId(string userId)
        {
            lock (_userConnections)
            {
                return _userConnections.FirstOrDefault(u => u.UserId == userId)?.ConnectionId;
            }
        }

        /// <summary>
        /// 根据 connectionId 获取 userId。
        /// </summary>
        public string? GetUserIdByConnectionId(string connectionId)
        {
            lock (_userConnections)
            {
                return _userConnections.FirstOrDefault(u => u.ConnectionId == connectionId)?.UserId;
            }
        }
    }

}
